package com.knowif.service;

import com.alibaba.fastjson.JSONObject;
import com.knowif.aliOSS.enumConfig.AliOSSConfig;
import com.knowif.aliOSS.service.AliyunFileUtil;
import com.knowif.dao.TUserMapper;
import com.knowif.dao.UserChatMapper;
import com.knowif.dao.UserOrderMapper;
import com.knowif.enumInfo.UserEnum;
import com.knowif.pojo.*;
import com.knowif.system.model.RestBean;
import com.knowif.util.WechatMiniUtil;
import com.knowif.util.commonUtil.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.*;

@Service
public class UserChatService {

    private Logger log = Logger.getLogger(UserChatService.class);//括号里面放的是当前类的class文件。

    @Autowired
    private UserChatMapper userChatMapper;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private AliyunFileUtil aliyunFileUtil;
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private WechatMiniUtil wechatMiniUtil;
    @Autowired
    private UserWechat_service userWechat_service;

    public RestBean<?> addUserChat(MessageChat userChat){
        int i = userChatMapper.insertSelective(userChat);
        log.info("私信"+ JSONObject.toJSONString(userChat));
        if(i > 0){
            TUser tUser = tUserMapper.selectByPrimaryKey(userChat.getParentId());
            TUser tUser1 = tUserMapper.selectByPrimaryKey(userChat.getUserId());
            String openid = tUser.getOpenid();
            UserWechat userWechat = userWechat_service.selectByMiniOpenid(openid);
            log.info("私信opneid信息" + JSONObject.toJSONString(userWechat));
            if(userWechat != null){
                List<Map<String,String>> list = new LinkedList<>();
                Map<String,String> map1 = new HashMap<>();
                map1.put("value",tUser1.getFullName());
                list.add(map1);
                map1 = new HashMap<>();
                map1.put("value",userChat.getContent());
                list.add(map1);
                map1 = new HashMap<>();
                map1.put("value", DateUtils.formatDateTime(new Date()));
                list.add(map1);
                String accessToken = (String) servletContext.getAttribute("wechatAccessToken");
                log.info("私信accessToken" + accessToken);
                wechatMiniUtil.sendTemplate(accessToken,"您有一条新私信，点击进入小程序-订单详情页-私信，立即查看！",userWechat.getPlatform(),list,
                        "",0,"13pcJvDa5CBb6P1fFMII2rZ-1Cf7QEvJZL-rd3uaVpY");
            }


            simpMessagingTemplate.convertAndSendToUser(openid,"/oop",RestBean.buildSuccess(userChat));
            return RestBean.buildSuccess("");
        }else{
            return RestBean.buildError();
        }
    }

    public RestBean<?> selectChatByOrderId(int userOrderId){
        return RestBean.buildSuccess("");
    }

    public RestBean<?> selectByParendId(Integer id){
        return RestBean.buildSuccess(userChatMapper.selectByParendId(id));
    }

    public RestBean<?> updateImage(MultipartFile image){
        if(image == null || image.isEmpty()) {
            return RestBean.buildError("无法读取图片");
        }else{
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
            String fileName = uuid;
            String suffix ="."+ image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf(".")+1);
            fileName = (fileName + suffix).toUpperCase();
            try {
            	aliyunFileUtil.fileUpload(AliOSSConfig.ALIIMAGE_STUDENT.setFileName(fileName),image.getInputStream());
                return RestBean.buildSuccess(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return RestBean.buildError("系统异常");
            }
        }
    }

    public RestBean<?> selectUserChatListByType(int userId,int orderId){
        TUser tUser = tUserMapper.selectByPrimaryKey(userId);
        UserOrder userOrder = userOrderMapper.selectByPrimaryKey(orderId);
        if(UserEnum.isUser(tUser.getUserType())){
            int toUserId = userOrder.getToUserId();//对方的userId
            List<UserChat> chats = userChatMapper.selectByOrderUserType(toUserId,orderId,userId);
            return RestBean.buildSuccess(chats);
        }else if (UserEnum.isTutor(tUser.getUserType())){
            int toUserId = userOrder.getUserId();
            List<UserChat> chats = userChatMapper.selectByOrderUserType(toUserId,orderId,userId);
            return RestBean.buildSuccess(chats);
        }else{

        }
        return RestBean.build();
    }

    public RestBean<?> selectUserChatList(int orderId){
        return RestBean.buildSuccess(userChatMapper.selectByOrderId(orderId));
    }


}
